<template>
  <div id="RoomPriceSetting">
    <div class="content">
      <div class="overflow-auto">
        <!-- 右侧内容部分 -->
        <div class="settingBody">
          <!-- 选择渠道 -->
          <div class="btnGroup">
            <el-button :type="item.isSelect ? 'primary' : ''" v-for="(item, index) in channels" :key="item.channel_id"
              @click="selectChannel(index)">{{ item.name }}</el-button>
          </div>
          <!-- END选择渠道 -->

          <!-- 筛选 -->
          <div class="screen">
            <div class="screen_date">
              <!-- 左右两侧箭头标签 -->
              <div class="screen_date_icon" style="margin-right: -1px" @click="icon_screenDate(0)">
                <i class="el-icon-arrow-left"></i>
              </div>
              <el-date-picker placeholder="选择日期" v-model="nowTime" size="small" :default-value="new Date()"
                style="width:150px;" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type=date>
              </el-date-picker>
              <div class="screen_date_icon" style="margin-left: -1px" @click="icon_screenDate(1)">
                <i class="el-icon-arrow-right"></i>
              </div>
            </div>

            <div class="screen_select">
              <el-select size="small" v-model="nowRoomType_id">
                <el-option v-for="(item, index) in roomTypeOption" :key="index" :label="item.room_title"
                  :value="item.room_id">
                </el-option>
              </el-select>
            </div>
            <div class="screen_switch">
              <el-switch v-model="switchValue"></el-switch>
              {{ switchValue ? '开启库存' : '关闭库存' }}
            </div>
          </div>
          <!-- END筛选 -->

          <!-- 表格 -->
          <div class="tableData">
            <el-table :data="roomType" border :key="refreshTable">
              <!-- fixed -->
              <el-table-column width="130" prop="room_title" align="center">
                <!-- label="本地房型"  -->
                <template slot="header">
                  <div>本地房型</div>
                </template>
              </el-table-column>

              <el-table-column width="120" v-for="(item, index) in dataArr" :key="index" align="center">
                <template slot="header">
                  <div class="table-date">
                    <div :style="{ 'color': new Date(item).getDay() == 0 || new Date(item).getDay() == 6 ? 'red' : '' }">
                      <div>{{ handleDate(item) }}</div>
                      <div>{{ handlweek(item) }}</div>
                    </div>
                  </div>
                </template>
                <!-- <template slot> -->
                <template slot-scope="{row}">
                  <div class="table_date_td" @click="openDrawer(item, row)">
                    <div>￥{{ row[item] ? parseInt(row[item].room_price) : '-' }}</div>
                    <div v-if="switchValue">剩 {{ row[item] ? row[item].stock_num : '-' }} 间</div>
                  </div>
                </template>
              </el-table-column>

            </el-table>

          </div>
          <!--END 表格 -->

        </div>

      </div>
    </div>

    <!-- 抽屉 -->
    <el-drawer title="修改价格" size="400px" :visible.sync="isShowDrawer" direction="rtl" custom-class="demo-drawer"
      ref="drawer">
      <div class="demo-drawer__content" style="padding: 20px;">
        <el-form :model="setPriceForm" label-width="70px">
          <el-form-item label="本地房型">
            {{ this.setPriceForm.room_title }}
          </el-form-item>
          <el-form-item label="改价日期">
            <el-date-picker size="small" style="width: 100%;" v-model="setPriceForm.date" type="daterange"
              range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="门市价">
            <!-- prefix-icon="el-icon-search" -->
            <el-input size="small" v-model="setPriceForm.price">
              <span slot="prefix">￥</span>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer" style="position: absolute;bottom: 30px;right: 30px;">
          <el-button size="small" @click="isShowDrawer == false">取 消</el-button>
          <el-button size="small" type="primary" @click="submit()">保存</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { price_room } from '@/api/hotel'
import { getChannel } from '@/api/channel'
import { mapState } from 'vuex'
export default {
  Name: 'ConsumptionSetting',
  components: {
  },
  computed: {
    ...mapState('d2admin/hotel', [
      'hotel_id'
    ])
  },
  data() {
    return {
      value: false,
      switchValue: true,
      channels: [],//渠道
      nowChannel: {},//当前选中渠道
      nowTime: new Date(),//选择时间
      roomType: [],//房型数组
      roomTypeOption: [],//选择房型选项
      nowRoomType: {},//当前选中房型
      nowRoomType_id: null,//当前选中房型id
      dataArr: [],//日期数组
      isShowDrawer: false,
      setPriceForm: {
        room_title: '',
        price: 0,
        room_id: null,
        start_date: '',
        end_date: '',
        date: '',
      },
      start_date: null,//开始
      end_date: null,//结束
      refreshTable: true,//table表格key值
    }
  },
  watch: {
    nowRoomType_id(n) {
      this.screenRoomtype()
    },
    nowTime(n) {
      console.log(n, '最新选择的日期');
      if (n == null) {
        n = new Date()
      }
      this.start_date = n
      this.end_date = this.getdaysAgo(n, 20)
      this.dataArr = this.getDateArr(this.start_date, this.end_date)
      this.refreshTable = !this.refreshTable
      // console.log(this.getDateArr(this.start_date, this.end_date), 'getDateArr');
      this.screenRoomtype()
    },

  },
  created() {
    this.init()
    this.dataArr = this.getDateArr(this.nowTime, this.getdaysAgo(this.nowTime, 20))
  },
  mounted() {
  },

  methods: {
    // 保存
    submit() {
      console.log(this.nowChannel, 'nowChannel');
      let setPrice = {
        hotel_id: sessionStorage.getItem('hotel_id'),
        room_id: this.setPriceForm.room_id,
        start_date: this.setPriceForm.date[0],
        end_date: this.setPriceForm.date[1],
        price: this.setPriceForm.price,
        channel_id: this.nowChannel.channel_id
      }
      price_room(setPrice, 'PUT').then(res => {
        let { code, message } = res.data
        if (code == 200) {
          this.$message({
            message: message,
            type: 'success'
          });
          this.isShowDrawer = false
          this.init()
        } else {
          this.$message({
            message: message,
            type: 'error'
          });
          this.isShowDrawer = false
        }

      })
    },

    /**
     * 选择渠道
     * @param {*} index 选择渠道下标
     */
    selectChannel(index) {
      this.channels.forEach(item => {
        item.isSelect = false
      })
      this.channels[index].isSelect = true
      this.nowChannel = this.channels[index]
      console.log(this.nowChannel, 'nowChannel');
      this.getRoomtype()
    },
    init() {
      /**获取渠道 */
      let getChannelData = {
        hotel_id: sessionStorage.getItem('hotel_id')
      }
      getChannel(getChannelData).then(res => {
        let { code, data } = res.data
        if (200 == code) {
          data = data.map((item, index) => {
            item.isSelect = false
            if (index == 0) {
              item.isSelect = true
            }
            return item
          })
          this.channels = data
          this.nowChannel = this.channels[0]
          this.getRoomtype()
          // console.log(this.nowChannel, 'nowChannel');
        }
      })

    },
    /**
     * 初次获取房型 给初始值
     */
    getRoomtype() {
      let getRoomData = {
        hotel_id: sessionStorage.getItem('hotel_id'),
        channel_id: this.nowChannel.channel_id,
        room_id: null
      }
      this.roomTypeOption = []
      price_room(getRoomData, 'GET').then(res => {
        let { code, data } = res.data
        // console.log(data, '获取房型');
        if (200 == code) {
          this.roomType = data
          // 下拉框options列表
          for (let i = 0; i < this.roomType.length; i++) {
            this.roomTypeOption.push({
              room_id: this.roomType[i].room_id,
              room_title: this.roomType[i].room_title
            })
          }
          this.roomTypeOption.unshift({
            room_id: null,//可获取所有房型
            room_title: '全部本地房型'
          })
          this.nowRoomType_id = this.roomTypeOption[0].room_id//默认选中第一个
        }
      })

    },
    /**
     * 筛选房型
     */
    screenRoomtype() {
      let screenRoomtype = {
        hotel_id: sessionStorage.getItem('hotel_id'),
        channel_id: this.nowChannel.channel_id,
        room_id: this.nowRoomType_id,
        start_date: this.start_date,
        end_date: this.end_date,
      }
      console.log(screenRoomtype, 'screenRoomtype');
      price_room(screenRoomtype, 'GET').then(res => {
        let { code, data } = res.data
        console.log(res, '获取房型');
        if (200 == code) {
          this.roomType = data
        }
      })
    },
    // 转换日期
    /**
     * 2021-11-22格式转11-22格式
     * @param {*} val 2021-11-22
     */
    handleDate(val) {
      if (val) {
        val = val.substring(5)
        return val
      }
    },

    /**
     * 转换周*
     * @param {*} val 
     */
    handlweek(val) {
      let week = ''
      val = new Date(val).getDay()
      switch (val) {
        case 0:
          week = "周日"
          break;
        case 1:
          week = "周一"
          break;
        case 2:
          week = "周二"
          break;
        case 3:
          week = "周三"
          break;
        case 4:
          week = "周四"
          break;
        case 5:
          week = "周五"
          break;
        case 6:
          week = "周六"
          break;
      }
      return week
    },
    /**
     * 传入日期，获取之后20天的日期
     * @param {date} n 当前日期
     * @param {int} days 当前日期
     * @param {bool} before true,获取当前日期之前的日期，不传入则获取之后的日期
     * @return 返回days后的日期
     */
    getdaysAgo(n, days, before) {
      let startDate = new Date(n);
      let endDate = new Date(startDate.getTime() + (days * 24 * 60 * 60 * 1000));

      if (before == true) {
        endDate = new Date(startDate.getTime() - (days * 24 * 60 * 60 * 1000));
      }
      let year = endDate.getFullYear();
      let month = String(endDate.getMonth() + 1).padStart(2, "0");
      let day = String(endDate.getDate()).padStart(2, "0");
      let formattedEndDate = `${year}-${month}-${day}`;
      return formattedEndDate
    },
    /**
     *  获取开始日期和结束日期期间的数组
     * @param {*} startDate 开始日期
     * @param {*} endDate 结束日期
     */

    getDateArr(startDate, endDate) {
      startDate = new Date(startDate)
      endDate = new Date(endDate)

      const dates = [];
      let currentDate = startDate;
      while (currentDate <= endDate) {
        const year = currentDate.getFullYear();
        const month = String(currentDate.getMonth() + 1).padStart(2, "0");
        const day = String(currentDate.getDate()).padStart(2, "0");
        const formattedDate = `${year}-${month}-${day}`;
        dates.push(formattedDate);

        currentDate.setDate(currentDate.getDate() + 1);
      }
      this.$set(dates)
      // this.dataArr = dates
      // console.log(dates);
      return dates
    },
    /**
     * 图标改变日期
     * @param {*} n 0，往前的日期  1，往后的日期 
     * 改变当前日期this.nowTime  触发到监听this.nowTime，
     */
    icon_screenDate(n) {
      if (n) {
        // console.log('三周后日期');
        this.nowTime = this.getdaysAgo(this.nowTime, 21)
      } else {
        // console.log('三周前日期');
        this.nowTime = this.getdaysAgo(this.nowTime, 21, true)
      }
    },

    /**
     * 打开对话框
     * @param {*} info 传入的信息
     */
    openDrawer(time, row) {
      let date = [time, time]
      this.setPriceForm.room_title = row.room_title
      this.setPriceForm.date = date
      this.setPriceForm.price = parseInt(row[time].room_price)
      this.setPriceForm.room_id = row.room_id
      this.isShowDrawer = true
    },


  }
}
</script>

<style lang="scss" scoped>
.overflow-auto {
  width: calc(100% - 190px);
  padding: 20px;

}

.settingBody {
  width: calc(100% - 190px);
  height: calc(100% - 50px);

  .btnGroup {
    height: 40px;
  }

  .screen {
    margin: 20px 0 30px 0;
    height: 34px;
    line-height: 32px;
    // background-color: #89a4e6;

    .screen_date {
      display: flex;
      // width: 210px;
      height: 32px;
      float: left;
      overflow: hidden;
      border: 1px solid #bfc0c4;
      background-color: white;

      .screen_date_icon {
        height: 32px;
        width: 26px;
        text-align: center;
        background-color: white;
      }

      .screen_date_icon :hover {
        cursor: pointer;
      }
    }

    .screen_select {
      float: left;
      margin-left: 20px;
      height: 32px;
      border: 1px solid #bfc0c4;
      background-color: white;
    }

    .screen_switch {
      float: right;

    }
  }

  .tableData {
    // background-color: #4e67a1;
    width: 100%;
    height: calc(100% - 130px);
  }

  .table_date_td {
    // background-color: red;
    width: 100px;
  }
}

::v-deep .el-date-editor.el-input.el-input--small.el-input--prefix.el-input--suffix.el-date-editor--date {

  // background-color: #aec2d4;
  .el-input__inner {
    border: none;
    height: 30px;
    border-radius: 0;
    width: 150px;
  }
}

// 选择器边框
::v-deep .el-select.el-select--small {
  .el-input__inner {
    border: none;
    height: 28px;
    width: 180px;
    border-radius: 0;
  }
}
</style>